
import { Component, ImageAsset, Sprite, SpriteFrame, Texture2D, _decorator, assetManager } from "cc";
import { Loger } from "../../loger/Loger";

const { ccclass, menu, property } = _decorator;

@ccclass
@menu("扩展组件/OnlineImage")
export default class OnlineImage extends Component {


    @property({ tooltip: "图片地址" })
    url: string = "";
    @property({ tooltip: "图片后缀名" })
    type: string = "";
    private onlineTexture: Texture2D = null;
    private sprite: Sprite = null;
    private callback: (succeed: boolean) => void = null;
    onLoad() {
        this.sprite = this.node.getComponent(Sprite)
    }

    start() {
        if (this.url) {
            this.loadImg(this.url, this.type);
        }
    }

    onDestory() {
        this.sprite.spriteFrame = null;
        this.sprite = null;
        if (this.onlineTexture) {
            assetManager.releaseAsset(this.onlineTexture);
            this.onlineTexture = null;
        }
    }

    loadImg(url: string, type: string = ".png", callback: (succeed: boolean) => void = null) {
        if (!url || url == "") {
            this.sprite.spriteFrame = null;
            callback(false);
            return;
        }
        this.callback = callback;
        let extObj = {};
        if(url.indexOf('.png') > 0 || url.indexOf('.jpg') > 0){
            extObj = {};
        }else{
            extObj = { ext: type };
        }
        assetManager.loadRemote<ImageAsset>(url, extObj, (err, res: ImageAsset) => {
            if (err) {
                if (this.callback) {
                    this.callback(false)
                    this.callback = null
                }
                Loger.error(err);
                return;
            } else {
                if (!this.sprite) {
                    if (this.callback) {
                        this.callback(false)
                        this.callback = null
                    }
                    Loger.error("container为空")
                    return;
                }
                if (!res) {
                    if (this.callback) {
                        this.callback(false)
                        this.callback = null
                    }
                    Loger.error("texture为空")
                    return;
                }
                const texture = new Texture2D();
                const spriteFrame = new SpriteFrame();
                texture.image = res;
                this.onlineTexture = texture;
                spriteFrame.texture = texture;
                spriteFrame.packable = false;
                this.sprite.spriteFrame = spriteFrame;
                if (this.callback) {
                    this.callback(true)
                    this.callback = null
                }
            }
        });
    }
}